#!/bin/bash
# ========================================
# RedFire 简化架构数据库初始化脚本
# ========================================

set -e

# 配置参数
DB_HOST="localhost"
DB_PORT="3306"
DB_USER="root"
DB_PASS="root"
DB_NAME="redfire_unified"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查MySQL连接
check_mysql_connection() {
    log_info "检查MySQL连接..."
    
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" -e "SELECT 1" >/dev/null 2>&1; then
            log_info "MySQL连接成功！"
            return 0
        fi
        
        log_warn "MySQL连接失败，等待重试... ($attempt/$max_attempts)"
        sleep 2
        ((attempt++))
    done
    
    log_error "无法连接到MySQL服务器"
    exit 1
}

# 创建数据库
create_database() {
    log_info "创建数据库 $DB_NAME..."
    
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" -e "
        CREATE DATABASE IF NOT EXISTS $DB_NAME 
        CHARACTER SET utf8mb4 
        COLLATE utf8mb4_unicode_ci;
    "
    
    log_info "数据库创建成功！"
}

# 执行SQL脚本
execute_sql_script() {
    local script_file="$1"
    
    if [ ! -f "$script_file" ]; then
        log_error "SQL脚本文件不存在: $script_file"
        exit 1
    fi
    
    log_info "执行SQL脚本: $script_file"
    
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" < "$script_file"
    
    if [ $? -eq 0 ]; then
        log_info "SQL脚本执行成功！"
    else
        log_error "SQL脚本执行失败！"
        exit 1
    fi
}

# 验证数据库结构
verify_database_structure() {
    log_info "验证数据库结构..."
    
    # 检查VnPy核心表
    local vnpy_tables=("dbbardata" "dbtickdata" "dbcontractdata" "dbbaroverview")
    for table in "${vnpy_tables[@]}"; do
        local count=$(mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" -sN -e "
            SELECT COUNT(*) FROM information_schema.tables 
            WHERE table_schema = '$DB_NAME' AND table_name = '$table'
        ")
        
        if [ "$count" -eq 1 ]; then
            log_info "✓ VnPy核心表 $table 存在"
        else
            log_error "✗ VnPy核心表 $table 不存在"
            exit 1
        fi
    done
    
    # 检查业务表
    local business_tables=("users" "trading_orders" "trading_trades" "user_positions" "user_accounts")
    for table in "${business_tables[@]}"; do
        local count=$(mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" -sN -e "
            SELECT COUNT(*) FROM information_schema.tables 
            WHERE table_schema = '$DB_NAME' AND table_name = '$table'
        ")
        
        if [ "$count" -eq 1 ]; then
            log_info "✓ 业务表 $table 存在"
        else
            log_error "✗ 业务表 $table 不存在"
            exit 1
        fi
    done
    
    log_info "数据库结构验证通过！"
}

# 验证用户权限
verify_user_permissions() {
    log_info "验证用户权限..."
    
    # 检查应用用户
    local app_user_exists=$(mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" -sN -e "
        SELECT COUNT(*) FROM mysql.user WHERE user = 'redfire_app'
    ")
    
    if [ "$app_user_exists" -gt 0 ]; then
        log_info "✓ 应用用户 redfire_app 存在"
    else
        log_error "✗ 应用用户 redfire_app 不存在"
        exit 1
    fi
    
    # 检查只读用户
    local readonly_user_exists=$(mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" -sN -e "
        SELECT COUNT(*) FROM mysql.user WHERE user = 'redfire_readonly'
    ")
    
    if [ "$readonly_user_exists" -gt 0 ]; then
        log_info "✓ 只读用户 redfire_readonly 存在"
    else
        log_error "✗ 只读用户 redfire_readonly 不存在"
        exit 1
    fi
    
    log_info "用户权限验证通过！"
}

# 显示数据库信息
show_database_info() {
    log_info "数据库信息:"
    
    echo "----------------------------------------"
    echo "数据库名称: $DB_NAME"
    echo "主机地址: $DB_HOST:$DB_PORT"
    echo "管理员用户: $DB_USER"
    echo "管理员密码: $DB_PASS"
    echo "应用用户: redfire_app"
    echo "应用密码: root"
    echo "只读用户: redfire_readonly"
    echo "只读密码: root"
    echo "----------------------------------------"
    
    # 显示表统计
    log_info "表统计信息:"
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" -e "
        SELECT 
            table_name as '表名',
            table_rows as '记录数',
            ROUND(((data_length + index_length) / 1024 / 1024), 2) as '大小(MB)',
            table_comment as '说明'
        FROM information_schema.tables 
        WHERE table_schema = '$DB_NAME'
        ORDER BY table_name;
    "
}

# 创建数据目录
create_data_directories() {
    log_info "创建数据目录..."
    
    local dirs=("../data/mysql" "../data/redis" "../logs/mysql" "../logs/redis")
    
    for dir in "${dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            log_info "创建目录: $dir"
        else
            log_info "目录已存在: $dir"
        fi
    done
}

# 主函数
main() {
    log_info "开始初始化RedFire简化架构数据库..."
    
    # 创建必要目录
    create_data_directories
    
    # 检查MySQL连接
    check_mysql_connection
    
    # 创建数据库
    create_database
    
    # 执行初始化脚本
    if [ -f "../schemas/mysql_business_only.sql" ]; then
        execute_sql_script "../schemas/mysql_business_only.sql"
    else
        log_error "找不到初始化脚本 mysql_business_only.sql"
        exit 1
    fi
    
    # 验证数据库结构
    verify_database_structure
    
    # 验证用户权限
    verify_user_permissions
    
    # 显示数据库信息
    show_database_info
    
    log_info "RedFire简化架构数据库初始化完成！"
    log_info "您可以使用以下方式访问数据库:"
    log_info "1. phpMyAdmin: http://localhost:8080"
    log_info "2. Redis Commander: http://localhost:8081"
    log_info "3. MySQL命令行: mysql -h localhost -u redfire_app -proot redfire_unified"
}

# 执行主函数
main "$@"
